<template>
  <BreadcrumbBar
    parent-label="Authority Management"
    child-label="Route Management"
  ></BreadcrumbBar>

  <InputForm>
    <InputItem label="条件查询路由" more-long="500">
      <el-cascader
        style="width: 100%"
        v-model="queryRouteSortId"
        :options="sortTree"
        :props="{ checkStrictly: true }"
        clearable
        placeholder="请选择上级分类（可选）"
        @visible-change="selectVisibleChangeHandler"
        size="large"
      />
    </InputItem>

    <ButtomItem label="操作">
      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="getRoutesList"
      >
        查询
      </el-button>

      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="() => emit('toggleType', 'tree')"
      >
        切换树形展现
      </el-button>

      <el-button
        style="height: 100%"
        v-once-click
        color="#626aef"
        plain
        @click="openCreateRouteDialog"
      >
        新建路由
      </el-button>
    </ButtomItem>
  </InputForm>

  <!-- 路由表格 -->
  <TableCard
    operation-bar-label="批量操作路由"
    :show-expand="50"
    :table-max-height="450"
  >
    <template #operationBar>
      <el-button
        v-once-click
        color="#626aef"
        plain
        size="small"
        @click="updateRoutesStatus(multipleSelectionItems, 0)"
      >
        启用
      </el-button>
      <el-button
        v-once-click
        type="info"
        size="small"
        @click="updateRoutesStatus(multipleSelectionItems, 1)"
      >
        禁用
      </el-button>
      <el-popconfirm
        title="确认删除"
        placement="right"
        @confirm="deleteRoutes(multipleSelectionItems)"
      >
        <template #reference>
          <el-button v-once-click color="#F56C6C" plain size="small">
            删除
          </el-button>
        </template>
      </el-popconfirm>
    </template>

    <template #table="{ maxHeight }">
      <el-table
        :data="querRouteList"
        stripe
        style="width: 100%"
        :max-height="maxHeight"
        @selection-change="handleSelectionChange"
        :headerCellStyle="tableHeaderCellStyle"
      >
        <el-table-column type="selection" width="30" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column property="enable" label="Enable" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.enable === 1" type="danger"> 禁用 </el-tag>
            <el-tag v-if="scope.row.enable === 0" type="success"> 启用 </el-tag>
          </template>
        </el-table-column>
        <el-table-column type="expand" label="详情" width="60">
          <template #default="props">
            <RouteDetail :route="props.row"></RouteDetail>
          </template>
        </el-table-column>
        <el-table-column property="name" label="Name" sortable width="160">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <div style="margin-right: 6px">{{ scope.row.name }}</div>
              <el-icon
                v-if="scope.row.isRedirect == 0"
                title="上级重定向路由"
                color="#eebe77"
                size="17"
              >
                <InfoFilled />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="path" label="Path" min-width="260" />
        <el-table-column
          property="description"
          label="Description"
          width="220"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <div style="margin-right: 6px">{{ scope.row.description }}</div>
              <el-icon
                v-if="scope.row.isNavigation == 0"
                title="历史导航路由"
                color="#eebe77"
                size="17"
              >
                <InfoFilled />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="Sort" width="360" show-overflow-tooltip>
          <template #default="scope">
            {{
              getDescriptionStr(findParentValues(sortTree, scope.row?.sortId))
            }}
          </template>
        </el-table-column>
        <el-table-column
          property="createTime"
          label="CreateTime"
          sortable
          width="180"
        />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-once-click
              type="info"
              size="small"
              v-if="scope.row.enable === 0"
              @click="updateRoutesStatus([scope.row.id], 1)"
            >
              禁用
            </el-button>
            <el-button
              v-once-click
              color="#626aef"
              plain
              size="small"
              v-if="scope.row.enable === 1"
              @click="updateRoutesStatus([scope.row.id], 0)"
            >
              启用
            </el-button>
            <el-button
              v-once-click
              color="#E6A23C"
              plain
              size="small"
              @click="
                openUpdateRouteDialog(
                  scope.row.id,
                  scope.row.path,
                  scope.row.name,
                  scope.row.component,
                  scope.row.componentPath,
                  scope.row.description,
                  scope.row.isRedirect,
                  scope.row.isNavigation,
                  scope.row.parentId,
                  scope.row.sortId
                )
              "
            >
              修改
            </el-button>
            <el-popconfirm
              title="确认删除"
              placement="left"
              @confirm="deleteRoutes([scope.row.id])"
            >
              <template #reference>
                <el-button v-once-click color="#F56C6C" plain size="small">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template #paginationBar>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :background="true"
        :total="total"
        :page-sizes="[20, 30, 40, 50, 60]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePageSizeChange"
        @current-change="handlePageNumChange"
      />
    </template>
  </TableCard>

  <!--  -->
  <!-- 路由创建对话框 -->
  <el-dialog
    v-model="createRouteDialogVisible"
    title="创建路由对话框"
    width="800px"
    draggable
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :before-close="closeRouteDialog"
  >
    <InputForm>
      <InputItem label="路由分类" more-long>
        <el-cascader
          v-model="tempRouteSortId"
          :options="sortTree"
          :props="{ checkStrictly: true }"
          placeholder="请选择路由分类"
          @visible-change="selectVisibleChangeHandler"
          style="width: 100%; height: 100%"
          size="large"
        />
      </InputItem>
      <InputItem label="上级路由" more-long>
        <!-- 分页下拉框 -->
        <PaginationSelect
          :selectValue="RouteParentId"
          :queryRouteSortId="tempRouteSortId"
          @selectValueChange="(val) => (RouteParentId = val)"
        ></PaginationSelect>
      </InputItem>
      <InputItem label="是否为上级路由的重定向路由">
        <el-select
          v-model="RouteIsRedirect"
          style="width: 100%; height: 100%"
          size="large"
        >
          <el-option label="非重定向路由" :value="1" />
          <el-option label="重定向路由" :value="0" />
        </el-select>
      </InputItem>
      <InputItem label="路由名称">
        <el-input
          v-model="RouteName"
          placeholder="请输入路由名称"
          maxlength="30"
          show-word-limit
          style="width: 100%; height: 100%"
        />
      </InputItem>
      <InputItem label="是否将该路径设置为历史导航">
        <el-select
          v-model="RouteIsNavigation"
          style="width: 100%; height: 100%"
          size="large"
        >
          <el-option label="非导航路由" :value="1" />
          <el-option label="导航路由" :value="0" />
        </el-select>
      </InputItem>
      <InputItem label="路由组件">
        <el-input
          v-model="RouteComponent"
          placeholder="请输入路由组件名称"
          maxlength="50"
          show-word-limit
          style="width: 100%; height: 100%"
        />
      </InputItem>
      <InputItem label="路由路径" more-long>
        <el-input
          v-model="RoutePath"
          placeholder="请输入路由路径"
          style="width: 100%; height: 100%"
        />
      </InputItem>
      <InputItem label="组件路径" more-long>
        <el-input
          v-model="RouteComponentPath"
          placeholder="请输入路由组件路径"
          style="width: 100%; height: 100%"
        />
      </InputItem>

      <InputItem label="路由页面描述" more-long>
        <el-input
          v-model="RouteDescription"
          placeholder="请输入路由页面描述"
          style="width: 100%; height: 100%"
        />
      </InputItem>
    </InputForm>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="closeRouteDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="createDialogConfirmHandler"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  -->
  <!-- 路由修改对话框 -->
  <el-dialog
    v-model="updateRouteDialogVisible"
    title="修改路由信息对话框"
    width="800px"
    draggable
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :before-close="closeRouteDialog"
  >
    <InputForm>
      <InputItem label="路由分类" more-long>
        <el-cascader
          v-model="tempRouteSortId"
          :options="sortTree"
          :props="{ checkStrictly: true }"
          placeholder="请选择路由分类"
          @visible-change="selectVisibleChangeHandler"
          style="width: 100%; height: 100%"
          size="large"
        />
      </InputItem>
      <InputItem label="上级路由" more-long>
        <!-- 分页下拉框 -->
        <PaginationSelect
          :selectValue="RouteParentId"
          :queryRouteSortId="tempRouteSortId"
          @selectValueChange="(val) => (RouteParentId = val)"
        ></PaginationSelect>
      </InputItem>
      <InputItem label="是否为上级路由的重定向路由">
        <el-select
          v-model="RouteIsRedirect"
          style="width: 100%; height: 100%"
          size="large"
        >
          <el-option label="非重定向路由" :value="1" />
          <el-option label="重定向路由" :value="0" />
        </el-select>
      </InputItem>
      <InputItem label="路由名称">
        <el-input
          v-model="RouteName"
          placeholder="请输入路由名称"
          maxlength="30"
          show-word-limit
          style="width: 100%; height: 100%"
        />
      </InputItem>
      <InputItem label="是否将该路径设置为历史导航">
        <el-select
          v-model="RouteIsNavigation"
          style="width: 100%; height: 100%"
          size="large"
        >
          <el-option label="非导航路由" :value="1" />
          <el-option label="导航路由" :value="0" />
        </el-select>
      </InputItem>
      <InputItem label="路由组件">
        <el-input
          v-model="RouteComponent"
          placeholder="请输入路由组件名称"
          maxlength="50"
          show-word-limit
          style="width: 100%; height: 100%"
        />
      </InputItem>
      <InputItem label="路由路径" more-long>
        <el-input
          v-model="RoutePath"
          placeholder="请输入路由路径"
          style="width: 100%; height: 100%"
        />
      </InputItem>
      <InputItem label="组件路径" more-long>
        <el-input
          v-model="RouteComponentPath"
          placeholder="请输入路由组件路径"
          style="width: 100%; height: 100%"
        />
      </InputItem>
      <InputItem label="路由页面描述" more-long>
        <el-input
          v-model="RouteDescription"
          placeholder="请输入路由页面描述"
          style="width: 100%; height: 100%"
        />
      </InputItem>
    </InputForm>

    <template #footer>
      <div>
        <el-button
          style="width: 120px"
          color="#909399"
          plain
          @click="closeRouteDialog"
        >
          取消
        </el-button>
        <el-button
          style="width: 120px"
          color="#626aef"
          @click="updateDialogConfirmHandler"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { storeToRefs } from 'pinia'
import { useSortTreeStore, useThemeStore } from '@/features/store/store'
import { useMessageAlertStore } from '@/features/store/componentStore'
import {
  getRoutesListApi,
  setRouteApi,
  deleteRoutesApi,
  updateRoutesStatusAPi,
} from '@/request/api/routes'

import PaginationSelect from './components/paginationSelect.vue'
import RouteDetail from './components/routeDescription.vue'
import InputForm from '@/components/InputForm/InputForm.vue'
import InputItem from '@/components/InputForm/InputItem.vue'
import ButtomItem from '@/components/InputForm/ButtomItem.vue'
import TableCard from '@/components/TableCard/TableCard.vue'
import BreadcrumbBar from '@/components/BreadcrumbBar/BreadcrumbBar.vue'

const emit = defineEmits(['toggleType'])

const { originData } = storeToRefs(useSortTreeStore())
const { getSortList, formattingSortData, findParentValues, getDescriptionStr } =
  useSortTreeStore()

const { tableHeaderCellStyle } = useThemeStore()
const { openAlert } = useMessageAlertStore()

onMounted(() => {
  getRoutesList()
  selectVisibleChangeHandler(true)
})

// 经过筛选后的分类树形列表
const sortTree = ref<SortTreeItf[]>([])
// 下拉框显示回调函数
const selectVisibleChangeHandler = (visible: boolean) => {
  if (!visible) return
  if (originData.value.length === 0) getSortList()
  sortTree.value = formattingSortData(originData.value, null, 'page')
}

const total = ref<number>(0)
const pageNum = ref<number>(1)
const pageSize = ref<number>(20)
const handlePageNumChange = (val: number) => {
  pageNum.value = val
  getRoutesList()
}
const handlePageSizeChange = (val: number) => {
  pageSize.value = val
  getRoutesList()
}

// 路由分类id，包含所有上级分类id
const queryRouteSortId = ref<string[]>([])
// 查询到的路由列表
const querRouteList = ref<RouteItf[]>([])
// 获取路由列表
const getRoutesList = async () => {
  let sortId = ''
  const a = queryRouteSortId.value
  if (a && a.length > 0) sortId = a[a.length - 1]

  const res = await getRoutesListApi(pageNum.value, pageSize.value, sortId)
  if (res.code !== 200) return openAlert.error(res.message)
  // ElMessage.success('查询路由成功')
  querRouteList.value = res.data.records
  total.value = res.data.total
}

// 当前路由id
const currentRouteId = ref<string>('')
// 路由路径
const RoutePath = ref<string>('')
// 路由名称
const RouteName = ref<string>('')
// 路由组件
const RouteComponent = ref<string>('')
// 路由组件路径
const RouteComponentPath = ref<string>('')
// 路由描述
const RouteDescription = ref<string>('')
// 路由上级id
const RouteParentId = ref<string>('')
// 是否为重定向路由
const RouteIsRedirect = ref<0 | 1>(1)
// 是否对该路径进行导航设置
const RouteIsNavigation = ref<0 | 1>(1)
// 创建，修改路由时的分类id
const tempRouteSortId = ref<string[]>([])

// 创建路由对话框
const createRouteDialogVisible = ref(false)
// 修改路由对话框
const updateRouteDialogVisible = ref(false)

const openCreateRouteDialog = () => {
  createRouteDialogVisible.value = true
}
const openUpdateRouteDialog = (
  id: string,
  path: string,
  name: string,
  component: string,
  componentPath: string,
  description: string,
  isRedirect: 0 | 1,
  isNavigation: 0 | 1,
  parentId?: string,
  sortId?: string
) => {
  currentRouteId.value = id
  RoutePath.value = path
  RouteName.value = name
  RouteComponent.value = component
  RouteComponentPath.value = componentPath
  RouteDescription.value = description
  RouteIsRedirect.value = isRedirect
  RouteIsNavigation.value = isNavigation
  RouteParentId.value = parentId
  tempRouteSortId.value = findParentValues(sortTree.value, sortId)

  updateRouteDialogVisible.value = true
}
const closeRouteDialog = () => {
  createRouteDialogVisible.value = false
  updateRouteDialogVisible.value = false

  currentRouteId.value = ''
  RoutePath.value = ''
  RouteName.value = ''
  RouteComponent.value = ''
  RouteComponentPath.value = ''
  RouteDescription.value = ''
  RouteIsRedirect.value = 1
  RouteIsNavigation.value = 1
  RouteParentId.value = ''
  tempRouteSortId.value = []
}
const createDialogConfirmHandler = () => {
  createRoute()
  closeRouteDialog()
}
const updateDialogConfirmHandler = () => {
  updateRoute()
  closeRouteDialog()
}

// 创建路由
const createRoute = async () => {
  let sortId = ''
  const t = tempRouteSortId.value
  if (t && t.length > 0) sortId = t[t.length - 1]

  const res = await setRouteApi({
    path: RoutePath.value,
    name: RouteName.value,
    component: RouteComponent.value,
    componentPath: RouteComponentPath.value,
    description: RouteDescription.value,
    isRedirect: RouteIsRedirect.value,
    isNavigation: RouteIsNavigation.value,
    parentId: RouteParentId.value,
    sortId: sortId,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('路由创建成功！')
  getRoutesList()
}

// 修改路由信息
const updateRoute = async () => {
  let sortId = ''
  const t = tempRouteSortId.value
  if (t && t.length > 0) sortId = t[t.length - 1]

  const res = await setRouteApi({
    path: RoutePath.value,
    name: RouteName.value,
    component: RouteComponent.value,
    componentPath: RouteComponentPath.value,
    description: RouteDescription.value,
    isRedirect: RouteIsRedirect.value,
    isNavigation: RouteIsNavigation.value,
    parentId: RouteParentId.value,
    sortId: sortId,
    id: currentRouteId.value,
  })
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('路由修改成功！')
  getRoutesList()
}

// 多选路由选项
const multipleSelectionItems = ref<string[]>([])
const handleSelectionChange = (val: RouteItf[]) => {
  let ids: string[] = []
  for (let item of val) ids.push(item.id)
  multipleSelectionItems.value = ids
}

// 批量删除路由
const deleteRoutes = async (ids: string[]) => {
  const res = await deleteRoutesApi(ids)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('路由删除成功！')
  getRoutesList()
}

// 批量更新路由状态
const updateRoutesStatus = async (ids: string[], status: 0 | 1) => {
  const res = await updateRoutesStatusAPi(ids, status)
  if (res.code !== 200) return openAlert.error(res.message)
  ElMessage.success('路由状态更新成功！')
  getRoutesList()
}
</script>

<style lang="less" scoped>
// :deep(.my-label) {
//   background: #f0f9eb !important;
//   font-weight: bold !important;
//   color: #606266 !important;
// }
</style>
